#!/usr/bin/env python
# -*- coding: utf8 -*-
import unittest
import os
from PIL import Image
from StringIO import StringIO
import requests
from utils import *

class LoginFail(Exception):
    def __init__(self, msg='wrong verify code'):
        self._msg = msg
    def __str__(self):
        return repr(self._msg)


class Xunlei(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self._userid = ''
        self.sn = requests.session()
        # self.sn.proxies = {'http': 'http://127.0.0.1:8087'}
        self.login()

    def _password_process(self, verify_code):
        ''' 加密处理是两次md5'''
        password = md5(md5(self.password))
        password = md5(password + verify_code)
        return  password

    @property
    def userid(self):
        if not self._userid:
            self._userid = self.sn.cookies.get('userid')
        return self._userid

    def login(self):
        cachetime = current_timestamp()
        check_url = 'http://login.xunlei.com/check?u=%s&cachetime=%d' % (self.username, cachetime)
        self.sn.get(check_url)
        verify_code = self.sn.cookies.get('check_result')
        if verify_code:
            if len(verify_code)==1:
                res = self.sn.get('http://verify2.xunlei.com/image?cachetime={}'.format(int(time.time())))
                img = Image.open(StringIO(res.content))
                img.convert('RGB')
                img.save('verify.jpg')
                verify_code = raw_input('Please enter  verify code:')
                verify_code = verify_code.strip().upper()
            else:
                verify_code = verify_code[2:].upper()
            password = self._password_process(verify_code)
            res = self.sn.post('http://login.xunlei.com/sec2login/', data={'u': self.username,
                                'p': password,
                                'verifycode': verify_code})
            if not self.sn.cookies.get('sessionid'):
                raise LoginFail()
        else:
            raise LoginFail('may be network problem')

        pass
    def add_bt(self, path):
        fname = os.path.split(path)[1]
        upload_url = 'http://dynamic.cloud.vip.xunlei.com/interface/torrent_upload'
        info = self.sn.post(upload_url, files={fname:open(path, 'rb')}).content
        upload_success = re.search(r'<script>document\.domain="xunlei\.com";var btResult =(\{.*\});</script>', info, flags=re.S)
        if upload_success:
            print upload_success.group(0)
            bt = json.loads(upload_success.group(0))
            data = {'uid':self.uid, 'btname':bt['ftitle'],
                    'cid':bt['infoid'], 'tsize':bt['btsize'],
                    'findex':''.join(f['id']+'_' for f in bt['filelist']),
                    'size':''.join(f['subsize']+'_' for f in bt['filelist']),
                    'from':'0'}
            jsonp = 'jsonp%s' % current_timestamp()
            commit_url = 'http://dynamic.cloud.vip.xunlei.com/interface/bt_task_commit?callback=%s' % jsonp
            self.sn.post(commit_url, data=data)
            return bt['infoid']
        else:
            exists = re.search(r"parent\.edit_bt_list\((\{.*\}),'','0'\)", response, flags=re.S)
            if exists:
                bt = json.loads(exists.group(1))
                return bt['infoid']



class Vod(object):
    def __init__(self, xunlei):
        self.xunlei = xunlei
        self.sn = self.xunlei.sn

    def check(self, infohash):
        check_bt_url = 'http://i.vod.xunlei.com/submit/check_bt?infohash={0}'.format(infohash)
        res = self.sn.get(check_bt_url).json()
        print res

    def add_bt(self, path):
        infohash = magnet_hash(path).upper()
        return self.add_magnet(infohash)

    def add_magnet(self, magnet):
        magnet = magnet.upper() # ensure upoper case
        self.check(magnet)
        add_bt_url = 'http://i.vod.xunlei.com/req_add_record'
        payload = {'from': 'vlist', 'platform':0, 'userid': self.xunlei.userid,
                'sessionid': self.sn.cookies['sessionid'],
                'fold_id':0}
        data = {"urls": [{"id":"1","url":"bt://{}".format(magnet)}]}
        res = self.sn.post(add_bt_url, params=payload, data=json.dumps(data)).json()
        return res
def get_xunlei(username='', password=''):
    if not username:
        username = 'xiaoye0013'
        password = 'xiaoye0013'
    while True:
        try:
            xun =  Xunlei(username, password)
        except LoginFail as e:
            print e
        else:
            return xun


def get_vod(username='', password=''):
    xunlei = get_xunlei(username, password)
    return Vod(xunlei)


class TestXunlei(unittest.TestCase):
    def setUp(self):
        self.username = 'xiaoye0013'
        self.password = 'xiaoye0013'
        self.xunlei = Xunlei(self.username, self.password)
        print self.xunlei.sn.cookies.get('sessionid')
    @unittest.skip('ok')
    def test_add_bt(self):

        pass
    def test_vod_check(self):
        vod = Vod(self.xunlei)
#        vod.add_bt('test.torrent')
if __name__ == '__main__':
    unittest.main()


